package com.itheima.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.itheima.constant.MessageConstant;
import com.itheima.dao.OrderDao;
import com.itheima.entity.Result;
import com.itheima.pojo.Location;
import com.itheima.entity.PageResult;
import com.itheima.entity.QueryPageBean;
import com.itheima.dao.LocationDao;
import com.itheima.service.LocationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service(interfaceClass = LocationService.class)
@Transactional
public class LocationServiceImpl implements LocationService {
    @Autowired
    private LocationDao locationDao;
    @Autowired
    private OrderDao orderDao;

    /**
     * 查找所有的体检中心
     *
     * @return
     */
    @Override
    public List<Location> findAll() {
        return locationDao.findAll();
    }

    /**
     * 复杂分页查询体检中心地址
     *
     * @param queryPageBean
     * @return
     */
    @Override
    public PageResult queryPage(QueryPageBean queryPageBean) {
        // 获取参数
        Integer pageSize = queryPageBean.getPageSize();
        Integer currentPage = queryPageBean.getCurrentPage();
        // 开始分页
        PageHelper.startPage(currentPage, pageSize);
        Page<Location> page = locationDao.queryPage(queryPageBean.getQueryString());
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 添加地址
     *
     * @param location
     */
    @Override
    public Result addLocation(Location location) {
        try {
            //先根据地址名判断当前地址在数据库中是否已经存在
            Location locationInDB = locationDao.findLocationByLocationName(location.getLocation());
            if (locationInDB == null){
                //说明不存在 可以直接添加
                locationDao.addLocation(location);
                return new Result(true,MessageConstant.ADD_LOCATION_SUCCESS);
            }else {
                return new Result(false,"当前地址已存在,请勿重复添加!");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.ADD_LOCATION_FAIL);
        }

    }

    @Override
    public Result deleteById(Integer locationId) {
        //查询当前地址是否已经有预约,如果有,返回用户无法删除原因,没有则删除
        long count= orderDao.findLocationCountByLocationId(locationId);
        if(count>0){
            return new Result(false, MessageConstant.CANNOT_DELETE);
        }else {
            locationDao.deleteById(locationId);
            return new Result(true, MessageConstant.DELETE_LOCATION_SUCCESS);
        }

    }
}
